import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Tabs,
  Form,
  Icon,
  Modal,
  Table,
  Input,
  Upload,
  Select,
  Button,
  message,
  Popconfirm,
} from 'antd';
import GeneralTableComponent from 'components/GeneralTableComponent';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import GeneralFilterComponent from 'components/GeneralFilterComponent';
import token from '../../utils/token';
import {env, host} from '../../utils/request'

function buildAuthorization() {
  let tokenVal = token.get();
  return (token !== '') ? tokenVal : '';
}

const { Option } = Select;
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const Dragger = Upload.Dragger;

@connect(({ loanSupermarket, loading }) => ({
  loanSupermarket,
  loading: loading.models.loanSupermarket,
}))
@Form.create()
export default class LoanSupermarket extends PureComponent {
  state = {
    paramList:{
      pageNo: 1,
      pageSize: 10,
      dateRange: [],
      source: '',
      title: '',
      type: '',
      state: '',
    },
    addDialogVisible: false,
    edited: {
      id: '',
      imgUrl: '',
      title: '',
      type: '',
      limitMoney: '',
      lendTime: '',
      monthPercent: '',
      limitTime: '',
      linkUrl: '',
      state: '',
      sort: '',
    },
    showUpload: '',
  };

  componentWillMount() {
    const { paramList } = this.state;
    switch(this.props.location.pathname.split('/')[1]) {
      case 'operatingCenter':
        paramList.source = 'up';
      break;
      case 'operatingCenterForXbeauty':
        paramList.source = 'xbeauty';
      break;
      case 'operatingCenterForXflower':
        paramList.source = 'xflower';
      break;
      case 'operatingCenterForUpoint':
        paramList.source = 'upoint';
      break;
      default:
      break;
    }
  }

  componentDidMount() {
    const { paramList } = this.state;
    paramList.type = 'wait-to-repay';
    this.getCreditMarketData();
  }

  getCreditMarketData = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state;
    let paramBuf = {
      source: paramList.source,
      type: paramList.type,
      title: paramList.title,
      startTime: '',
      endTime: '',
      pageSize: paramList.pageSize,
      pageNo: paramList.pageNo,
      state: paramList.state == 'on' ? true : (paramList.state == 'off' ? false : ''),
    };
    if (paramList.dateRange[0]) {
      [paramBuf.startTime, paramBuf.endTime] = [paramList.dateRange[0].format('YYYY-MM-DD hh:mm:ss'), paramList.dateRange[1].format('YYYY-MM-DD hh:mm:ss')];
    }
    let postParam = {};
    for (let [key, val] of Object.entries(paramBuf)) {
      if (val !== '') {
        postParam[key] = val;
      }
    }
    dispatch({
      type: 'loanSupermarket/fetchGetAllCreditMarket',
      payload: {
        ...postParam
      }
    });
  };

  addLoanMarket = (dataList) => {
    const { form, dispatch } = this.props;
    const { edited, paramList } = this.state;
    let paramBuf = {
      imgUrl: dataList.imgUrl,
      title: dataList.title,
      type: dataList.type,
      limitMoney: dataList.limitMoney,
      lendTime: dataList.lendTime,
      monthPercent: dataList.monthPercent,
      limitTime: dataList.limitTime,
      linkUrl: dataList.linkUrl,
      source: paramList.source,
      state: dataList.state,
      sort: dataList.sort,
    };
    let postParam = {};
    for (let [key, val] of Object.entries(paramBuf)) {
      if (val !== '' && typeof(val) != 'undefined') {
        postParam[key] = val;
      }
    }
    dispatch({
      type: 'loanSupermarket/fetchPostAddCreditMarket',
      payload: {
        ...postParam
      },
      callback: (res) => {
        if (res.code == 200) {
          this.setState({
            addDialogVisible: false,
            showUpload: '',
          });
          edited.showUpload = '';
          form.resetFields();
          message.success(`添加成功`);
          this.getCreditMarketData();
        } else if (res.code == 400) {
          message.error(`${res.message}`);
        } else {
          message.error(`未知错误`);
        }
      }
    });
  };

  updateLoanMarket = (dataList) => {
    const { form, dispatch } = this.props;
    const { edited, paramList } = this.state;
    let paramBuf = {
      id: dataList.id,
      imgUrl: dataList.imgUrl,
      title: dataList.title,
      type: dataList.type,
      limitMoney: dataList.limitMoney,
      lendTime: dataList.lendTime,
      monthPercent: dataList.monthPercent,
      limitTime: dataList.limitTime,
      linkUrl: dataList.linkUrl,
      state: dataList.state,
      source: paramList.source,
      sort: dataList.sort,
    };
    let postParam = {};
    for (let [key, val] of Object.entries(paramBuf)) {
      if (val !== '' && typeof(val) != 'undefined') {
        postParam[key] = val;
      }
    }
    dispatch({
      type: 'loanSupermarket/fetchPostUpdateCreditMarket',
      payload: {
        ...postParam
      },
      callback: (res) => {
        if (res.code == 200) {
          this.setState({
            addDialogVisible: false,
            showUpload: '',
          });
          edited.id = '';
          edited.showUpload = '';
          form.resetFields();
          message.success(`修改成功`);
          this.getCreditMarketData();
        } else if (res.code == 400) {
          message.error(`${res.message}`);
        } else {
          message.error(`未知错误`);
        }
      },
    });
  };

  deleteData = (row) => {
    const { dispatch } = this.props;
    let postParam = {
      id: row.id
    };
    dispatch({
      type: 'loanSupermarket/fetchPostDelCreditMarket',
      payload: {
        ...postParam
      }
    }).then(() => {
      this.getCreditMarketData();
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { paramList } = this.state;
    paramList.pageNo = pagination.current;
    this.getCreditMarketData();
  };

  handleFormReset = (value) => {
    const { paramList } = this.state;
    Object.assign(paramList, value);
    paramList.pageNo = 1;
    this.getCreditMarketData();
  };

  handleFormSearch = (value) => {
    const { paramList } = this.state;
    Object.assign(paramList, value);
    paramList.pageNo = 1;
    this.getCreditMarketData();
  };

  showAddDialog = () => {
    const { edited } = this.state;
    edited.id = '';
    this.setState({
      addDialogVisible: true
    });
  };

  showEditDialog = (row) => {
    const { edited } = this.state;
    Object.assign(edited, row);
    this.setState({
      addDialogVisible: true
    });
  };

  showEditStatusDialog = (row) => {
    const { edited } = this.state;
    edited.id = row.id;
    this.setState({
      addDialogVisible: true
    });
  };

  handleTabChange = (value) => {
    const { paramList } = this.state;
    paramList.type = value;
    paramList.pageNo = 1;
    this.getCreditMarketData();
  };

  reSourceType = (src) => {
    let sourceType = [{
      value: '',
      label: '全部',
    }, {
      value: 'up',
      label: 'sdfz',
    // }, {
    //   value: 'xbeauty',
    //   label: '想美',
    // }, {
    //   value: 'xflower',
    //   label: '信花花',
    // }, {
    //   value: 'upoint',
    //   label: '有点',
    }];
    let reLabel = 'unknown';
    sourceType.forEach((val, index, arr) => {
      if (src == val.value) {
        reLabel = val.label
      }
    });
    return reLabel
  };

  handleAddOk = () => {
    const { form } = this.props;
    const { edited, paramList } = this.state;
    if (!!edited.id && edited.state) {
      //存在id && 状态为上线 只编辑状态
      form.validateFields((err, fieldsValue, ccc) => {
        if (fieldsValue.state) {
          let editParam = {
            id: edited.id,
            state: fieldsValue.state == 'on' ? true : (fieldsValue.state == 'off' ? false : ''),
          }
          this.updateLoanMarket(editParam);
        }
      });
    } else if(!edited.id) {
      //不存在id 保存添加
      form.validateFields((err, fieldsValue, ccc) => {
        if (!err) {
          let addParam = {
            imgUrl: '',
            title: fieldsValue.title,
            type: fieldsValue.type,
            limitMoney: fieldsValue.limitMoney,
            lendTime: fieldsValue.lendTime,
            monthPercent: fieldsValue.monthPercent,
            limitTime: fieldsValue.limitTime,
            linkUrl: fieldsValue.linkUrl,
            state: fieldsValue.state == 'on' ? true : (fieldsValue.state == 'off' ? false : ''),
            source: paramList.source,
            sort: fieldsValue.sort,
          }
          if (fieldsValue.image.file && fieldsValue.image.file.response && fieldsValue.image.file.response.data) {
            addParam.imgUrl = fieldsValue.image.file.response.data;
          }
          this.addLoanMarket(addParam);
        }
      });
    } else {
      //存在id && 状态为上线 编辑所有
      form.validateFields((err, fieldsValue, ccc) => {
        if (!err) {
          let editParam = {
            id: edited.id,
            imgUrl: '',
            title: fieldsValue.title,
            type: fieldsValue.type,
            limitMoney: fieldsValue.limitMoney,
            lendTime: fieldsValue.lendTime,
            monthPercent: fieldsValue.monthPercent,
            limitTime: fieldsValue.limitTime,
            linkUrl: fieldsValue.linkUrl,
            state: fieldsValue.state == 'on' ? true : (fieldsValue.state == 'off' ? false : ''),
            source: paramList.source,
            sort: fieldsValue.sort != edited.sort ? fieldsValue.sort : '',
          };
          if (fieldsValue.image.file && fieldsValue.image.file.response && fieldsValue.image.file.response.data) {
            editParam.imgUrl = fieldsValue.image.file.response.data;
          }
          this.updateLoanMarket(editParam);
        }
      });
    }
  };

  handleAddCancel = () => {
    const { edited } = this.state;
    const { form } = this.props;
    form.validateFields((err, fieldsValue, ccc) => {
      form.resetFields();
    });
    edited.id = '';
    edited.showUpload = '';
    this.setState({
      addDialogVisible: false,
      showUpload: '',
    });
  };

  handleUploadChange = (file, fileList) => {
    const { edited } = this.state;
    // const isJPG = file.type === 'image/jpeg';
    // if (!isJPG) {
    //   message.error('You can only upload JPG file!');
    // }
    // const isLt2M = file.size / 1024 / 1024 < 2;
    // if (!isLt2M) {
    //   message.error('Image must smaller than 2MB!');
    // }
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      this.setState({
        showUpload: reader.result,
      });
    }
  };

  render() {
    const { loanSupermarket: { allCreditMarketData }, loading, form } = this.props;
    const { edited, showUpload } = this.state;
    const { getFieldDecorator } = form;

    const tableColumns = [{
        title: '序号',
        dataIndex: 'demo',
        key: 'demo',
        render: (text, record, index) => {
          return <span>{index + 1 + ( allCreditMarketData.pagination.current - 1 ) * allCreditMarketData.pagination.size}</span>
        }
      }, {
        title: '产品类型',
        dataIndex: 'source',
        key: 'source',
        render: (text, record, index) => {
          return <span>{this.reSourceType(text)}</span>
        }
    }, {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
        render: val => `${val}`
      }, {
        title: '发布时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        render: val => `${val}`
      }, {
        title: '点击次数',
        dataIndex: 'clickNum',
        key: 'clickNum',
        render: val => `${val}`
      }, {
        title: '排序',
        dataIndex: 'sort',
        key: 'sort',
        render: val => `${val}`
      }, {
        title: '状态',
        dataIndex: 'state',
        key: 'state',
        render: (text, record, index) => {
          return text ? <span>已上架</span> : <span>已下架</span>
        }
      }, {
        title: '操作',
        dataIndex: 'demo6',
        key: 'demo6',
        render: (text, record, index) => {
          return  <div>
                    <Button type="primary" size="small" style={{marginRight: 8}} onClick={() => this.showEditDialog(record)}>修改</Button>
                    {
                      !record.state ?
                      <Popconfirm title="确认删除" onConfirm={() => this.deleteData(record)}>
                        <Button type="primary" size="small">删除</Button>
                      </Popconfirm> :
                      <Button type="primary" size="small" disabled>删除</Button>
                    }
                  </div>
        }
      }]

    const searchColumns = [{
    //   type: 'select',
    //   value: 'source',
    //   label: '产品类型',
    //   placeholder: '请选择',
    //   selectOption:  [{
    //     value: 'all',
    //     label: '全部',
    //   }, {
    //     value: 'up',
    //     label: 'sdfz',
    //   }, {
    //     value: 'xbeauty',
    //     label: '想美',
    //   }, {
    //     value: 'xflower',
    //     label: '信花花',
    //   }]
    // }, {
      type: 'select',
      value: 'state',
      label: '状态',
      placeholder: '请选择',
      selectOption:  [{
        value: 'all',
        label: '全部',
      }, {
        value: 'on',
        label: '已上线',
      }, {
        value: 'off',
        label: '已下线',
      }]
    }, {
      type: 'input',
      value: 'title',
      label: '标题',
      placeholder: '请输入',
    }, {
      type: 'rangePicker',
      value: 'dateRange',
      label: '发布时间',
      placeholder: ['起始时间', '结束时间'],
      format:'YYYY-MM-DD HH:mm:ss',
      showTime: true,
    }, {
      type: 'rangePicker',
      value: 'clickDateRange',
      label: '统计点击时间',
      placeholder: ['起始时间', '结束时间'],
      format:'YYYY-MM-DD HH:mm:ss',
      showTime: true,
    }];

    const formItemLayout =  {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
    };

    let vm = this;
    const uploadProps = {
      name: 'file',
      action: host[env] + '/user/creditMarket/upload/',
      headers: {
        Authorization: buildAuthorization(),
      },
      onChange(info) {
        const status = info.file.status;
        if (status !== 'uploading') {
          //
        }
        if (status === 'done') {
          message.success(`${info.file.name} 图片上传成功.`);
        } else if (status === 'error') {
          message.error(`${info.file.name} 图片上传失败.`);
          // form.resetFields(['']); //reset对image无效
          vm.setState({
            showUpload: ''
          });
        }
      },
    };

    const editedBuf = edited.id ? edited : {};
    const disableEdit = !!edited.state && edited.id;

    return (
      <PageHeaderLayout title="贷超配置">
        {
          !this.state.addDialogVisible ?
          <Card bordered={false}>
            <div style={{marginLeft: 27, marginBottom: 20}}>
              <Button onClick={this.showAddDialog}>新建</Button>
            </div>
            <div style={{marginBottom: 20}}>
              <GeneralFilterComponent
              itemList={searchColumns}
              onClear={this.handleFormReset}
              onSearch={this.handleFormSearch}
              ></GeneralFilterComponent>
            </div>

            <Tabs defaultActiveKey="wait-to-repay" onChange={this.handleTabChange}>
              <TabPane tab="待还款" key="wait-to-repay">
                <GeneralTableComponent
                  loading={loading}
                  data={allCreditMarketData}
                  columns={tableColumns}
                  onChange={this.handleStandardTableChange}
                />
              </TabPane>
              <TabPane tab="风控被拒绝" key="risk-fail">
                <GeneralTableComponent
                  loading={loading}
                  data={allCreditMarketData}
                  columns={tableColumns}
                  onChange={this.handleStandardTableChange}
                />
              </TabPane>
            </Tabs>
          </Card>
          :
          <Card bordered={false}>
            <Form layout={"horizontal"} onSubmit={this.handleAddOk}>
              <div>
                <FormItem label="状态" {...formItemLayout}>
                  {getFieldDecorator('state', {
                    rules: [{ required: true, message: '请选择状态' }],
                     initialValue: editedBuf.state === true ? 'on' : (editedBuf.state === false ? 'off' : undefined)
                  })(
                    <Select>
                      <Option value="on">上架</Option>
                      <Option value="off">下架</Option>
                    </Select>
                  )}
                </FormItem>
              </div>
              <div>
                <FormItem label="归属页面" {...formItemLayout}>
                  {getFieldDecorator('type', {
                    rules: [{ required: true, message: '请选择归属页面' }],
                    initialValue: editedBuf.type
                  })(
                    <Select disabled={disableEdit}>
                      <Option value="wait-to-repay">待还款</Option>
                      <Option value="risk-fail">风控被拒绝</Option>
                    </Select>
                  )}
                </FormItem>
              </div>
              {
                /*!edited.id ?
                <div>
                  <FormItem label="产品来源" {...formItemLayout}>
                    {getFieldDecorator('source', {
                      rules: [{ required: true, message: '请选择产品来源' }],
                    })(
                      <Select>
                        <Option value="up">sdfz</Option>
                        <Option value="xbeauty">想美</Option>
                        <Option value="xflower">信花花</Option>
                      </Select>
                    )}
                  </FormItem>
                </div>
                : ''*/
              }
              <div>
                <FormItem label="排序" {...formItemLayout}>
                  {getFieldDecorator('sort', {
                    rules: [{ required: true, message: '请输入排序值' }],
                    initialValue: editedBuf.sort
                  })(
                    <Input disabled={disableEdit} />
                  )}
                </FormItem>
              </div>
              <div>
                <FormItem label="标题" {...formItemLayout}>
                  {getFieldDecorator('title', {
                    rules: [{ required: true, message: '请输入标题' }],
                    initialValue: editedBuf.title
                  })(
                    <Input disabled={disableEdit} />
                  )}
                </FormItem>
              </div>
              <div>
                <FormItem label="借款额度" {...formItemLayout}>
                  {getFieldDecorator('limitMoney', {
                    rules: [{ required: true, message: '请输入借款额度' }],
                    initialValue: editedBuf.limitMoney
                  })(
                    <Input disabled={disableEdit} />
                  )}
                </FormItem>
              </div>
              <div>
                <FormItem label="放款时间" {...formItemLayout}>
                  {getFieldDecorator('lendTime', {
                    rules: [{ required: true, message: '请输入放款时间' }],
                    initialValue: editedBuf.lendTime
                  })(
                    <Input disabled={disableEdit} style={{width: 200}} />
                  )}
                </FormItem>
              </div>
              <div>
                <FormItem label="月利率" {...formItemLayout}>
                  {getFieldDecorator('monthPercent', {
                    rules: [{ required: true, message: '请输入月利率' }],
                    initialValue: editedBuf.monthPercent
                  })(
                    <Input disabled={disableEdit} />
                  )}
                </FormItem>
              </div>
              <div>
                <FormItem label="期限" {...formItemLayout}>
                  {getFieldDecorator('limitTime', {
                    rules: [{ required: true, message: '请输入期限' }],
                    initialValue: editedBuf.limitTime
                  })(
                    <Input disabled={disableEdit} />
                  )}
                </FormItem>
              </div>
              <div>
                <FormItem label="申请链接" {...formItemLayout}>
                  {getFieldDecorator('linkUrl', {
                    rules: [{ required: true, message: '请输入链接' }],
                    initialValue: editedBuf.linkUrl
                  })(
                    <Input disabled={disableEdit} />
                  )}
                </FormItem>
              </div>
              <div>
                <FormItem label="上传图片" {...formItemLayout}>
                  {getFieldDecorator('image', {
                    rules: [{ required: true, message: '请输入链接' }],
                    initialValue: editedBuf.imgUrl
                  })(
                    <Dragger disabled={disableEdit} {...uploadProps} showUploadList={false} beforeUpload={(file, fileList) => {this.handleUploadChange(file, fileList);}}>
                      {showUpload ? <img src={showUpload} style={{maxWidth: "100%"}} /> : (
                        editedBuf.imgUrl ?
                        <img src={editedBuf.imgUrl} style={{maxWidth: "100%"}} />
                        :
                        <div>
                          <p className="ant-upload-drag-icon">
                            <Icon type="inbox" />
                          </p>
                          <p className="ant-upload-text">点击此处选择文件 或者 拖拽文件到此处</p>
                        </div>
                        )
                      }
                    </Dragger>
                  )}
                </FormItem>
              </div>
              <div>
                <FormItem label="操作" {...formItemLayout}>
                  {(
                    <div style={{width: '100%', textAlign: 'center'}}>
                      <Popconfirm title="确认返回? 该页编辑的信息将会丢失" onConfirm={() => this.handleAddCancel()}>
                        <Button style={{marginRight: 20}}>取消</Button>
                      </Popconfirm>
                      <Button type="primary" htmlType="submit" >保存</Button>
                    </div>
                  )}
                </FormItem>
              </div>
            </Form>
          </Card>
        }
      </PageHeaderLayout>
    );
  }
}
